import 'package:flutter/material.dart' hide Form;
import 'package:get/get.dart';
import 'package:orginone/dart/extension/index.dart';
import 'package:orginone/components/form/form_widget/form_tool.dart';
import 'package:orginone/components/form/mapping_components.dart';

import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/core/thing/standard/form.dart';
import 'package:orginone/main.dart';

import '../../../XText/XText.dart';
import 'index.dart';

class MainFormPage extends GetView<MainFormController> {
  const MainFormPage(this.forms, {Key? key, this.infoIndex, this.form})
      : super(key: key);
  final Form? form;
  final List<XForm> forms;
  final int? infoIndex; //表单info需要展示第几个
  @override
  Widget build(BuildContext context) {
    return GetBuilder<MainFormController>(
      init: MainFormController(),
      id: "main_form",
      builder: (_) {
        return _buildView();
      },
    );
  }

  // 主视图
  Widget _buildView() {
    return <Widget>[
      _buildHeaderView(),
      _buildMainFormView(),
    ].toColumn();
  }

  _buildHeaderView() {
    if (forms.isEmpty) {
      return Container();
    }
    XForm xform = forms[0];
    return XText.boxTitle(xform.name ?? '主表');
    // .paddingTop(15);
  }

  _buildMainFormView() {
    if (forms.isEmpty) {
      return Container();
    }
    return _formListView();
  }

  _formListView() {
    List<FieldModel> fileds = forms.isNotEmpty ? forms.first.fields : [];
    //过滤隐藏字段
    fileds =
        fileds.where((element) => element.options?.hideField != true).toList();
    return ListView.builder(
      itemCount: fileds.length,
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemBuilder: (context, index) {
        FieldModel fieldModel = fileds[index];

        Map<String, dynamic> info = {};
        if (forms.first.data?.after.isNotEmpty ?? false) {
          info = forms.first.data!.after[infoIndex ?? 0].otherInfo;
        }

        return FutureBuilder<bool>(
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              return mappingComponents[fieldModel.field.type ?? ""]!(
                  fieldModel.field, relationCtrl.user!);
            }
            // LogUtil.d(
            //     "mappingComponents type:${fieldModel.field.type} title：${fieldModel.field.title}valueType${fieldModel.valueType}");
            return Container();
          },
          future: FormTool.loadMainFieldData(fieldModel, info),
        );
      },
    );
  }
}
